package org.example.myl.serial;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import org.springframework.stereotype.Component;

@Component
public class SerialCommunication {
    private SerialPort serialPort;

    public SerialCommunication() {
        initialize();
    }

    private void initialize() {
        // 列出所有可用的串口
        SerialPort[] ports = SerialPort.getCommPorts();
        for(SerialPort port : ports) {
            System.out.println(port.getSystemPortName());
        }

        // 假设我们选择第一个串口
        if (ports.length > 0) {
            serialPort = ports[0];
            serialPort.openPort();
            serialPort.setComPortParameters(9600, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
            serialPort.addDataListener(new SerialPortDataListener() {
                @Override
                public int getListeningEvents() {
                    return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
                }

                @Override
                public void serialEvent(SerialPortEvent event) {
                    if(event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
                        return;
                    byte[] newData = new byte[serialPort.bytesAvailable()];
                    int numRead = serialPort.readBytes(newData, newData.length);
                    System.out.println("Read " + numRead + " bytes.");
                    // 在这里处理你从电路板接收到的数据
                }
            });
        } else {
            System.out.println("没有找到可用的串口");
        }
    }

    public void close() {
        if(serialPort.isOpen()) {
            serialPort.closePort();
        }
    }
}
